package org.bp.spider.only;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.bp.spider.util.Pair;
import org.bp.spider.util.PropertiesReader;
import org.bp.spider.util.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class QueryCompany {
	public List<Company> queryCompany(String url, String cookiesFile) {
		Document document = null;
		try {
			// 这儿的SESSIONID需要根据要登录的目标网站设置的session Cookie名字而定
			Connection con = Jsoup.connect(url);
			// 设置访问形式（电脑访问，手机访问）：直接百度都参数设置
			con.header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
			// 把登录信息的cookies保存如map对象里面
			// 把登录的信息放入请求里面
			Properties properties = PropertiesReader.getProperties(cookiesFile);
			Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
			for (Map.Entry<Object, Object> entry : entrySet) {
				con.cookie(entry.getKey().toString(), entry.getValue().toString());
			}  
			// 再次获取Document对象。
			document = con.get();
			return parserDocument(document);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return null;
	}
	private List<Company> parserDocument(Document document){
		List<Company> list = new ArrayList<>();
		Company company = null;
		Elements elements = document.select(".col-2");
		for (int i = 1; i < elements.size(); i++) {
			company = new Company();
			// 公司名
			String companyName = elements.get(i).select(".company-title a").text();
			company.setName(companyName);

			// 处理其余信息
			Elements childNodes = elements.get(i).select(".legal-person");

			// 法定代表人
			Element personNameElement = childNodes.first();
			String personName = personNameElement.text().split("：")[1];
			company.setBoss(personName);

			// 地址
			Element addressNameElement = childNodes.last();
			String addressName = addressNameElement.text();
			company.setAddress(disposeAddress(addressName));

			// 邮箱 地址
			if (childNodes.size() > 2) {
				Element complex = childNodes.get(1);
				String text = complex.text();
				Pair<Integer, String> pair = disposeComplex(text);
				disposePair(pair, company);
			}

			list.add(company);
		}
		return list;
	}
	private void disposePair(Pair<Integer, String> pair, Company company) {
		switch (pair.getKey()) {
		case 1:
			break;
		case 2:
			company.setPhone(pair.getValue());
			break;
		case 3:
			company.setEmail(pair.getValue());
			break;
		case 4:
			String[] split = pair.getValue().split("&");
			company.setPhone(split[0]);
			company.setEmail(split[1]);
			break;
		}
	}

	private Pair<Integer, String> disposeComplex(String origin) {
		// 无电话邮箱
		if (StringUtils.isAbsEmpty(origin)) {
			return new Pair<>(1, "no phone and eamil");
		}
		// 只有电话
		if (!origin.contains("邮箱")) {
			return new Pair<>(2, origin.split("：")[1]);
		}
		// 只有邮箱
		if (!origin.contains("电话")) {
			return new Pair<>(3, origin.split("：")[1]);
		}
		// 都有
		String[] split = origin.split("邮箱：");
		StringBuilder builder = new StringBuilder(split[0].split("：")[1]);
		return new Pair<>(4, builder.append("&").append(split[1]).toString());
	}

	private String disposeAddress(String origin) {
		String address = origin.split("：")[1];
		return address.endsWith("查看地图") ? address.substring(0, address.length() - 4) : address;
	}
}
